app.controller('NavBarPanelCtrl', ['$scope', '$rootScope', '$element', '$location', '$http',
    function ($scope, $rootScope, $element, $location, $http) {
    $scope.logout = function() {
        $http.get('/logout')
            .success(function() {
                $location.path('/login');
                WebApp.currentUser = {};
                $rootScope.currentUser = WebApp.currentUser;
            });
    };
}]).directive('navBarPanel', function () {
    return {
        replace: true,
        controller: 'NavBarPanelCtrl',
        templateUrl: 'static/js/directives/nav-bar-panel.html'
    };
});

app.controller('CommentItemPanelCtrl', ['$scope', '$rootScope', '$element', '$location', '$http',
    function ($scope, $rootScope, $element, $location, $http) {

    }]).directive('commentItemPanel', function () {
    return {
        replace: true,
        controller: 'CommentItemPanelCtrl',
        templateUrl: 'static/js/directives/comment-item-panel.html'
    };
});

app.controller('FooterBarPanelCtrl', ['$scope', '$rootScope', '$element', '$location', '$http',
    function ($scope, $rootScope, $element, $location, $http) {
        $scope.logout = function () {
            $http.get('/logout')
                .success(function () {
                    $location.path('/login');
                    WebApp.currentUser = {};
                    $rootScope.currentUser = WebApp.currentUser;
                });
        };
    }]).directive('footerBarPanel', function () {
    return {
        replace: true,
        controller: 'FooterBarPanelCtrl',
        templateUrl: 'static/js/directives/footer-bar-panel.html'
    };
});

function addScript(url, callback) {
    var elt = document.createElement("script");
    elt.src = url;
    elt.anysc = true;
    if (elt.onload == null) {
        elt.onload = function () {
            typeof callback == 'function' && callback();
        }
    } else {
        elt.onreadystatechange = function () {
            if (elt.readyState == "loaded" || elt.readyState == "complete") {
                typeof callback == 'function' && callback();
            }
        }
    }
    document.getElementsByTagName("body")[0].appendChild(elt);
}

app.directive('ueditor',
    function () {
        return {
            restrict: 'EA',
            require: 'ngModel',
            scope: {
                height: '@?'
            },
            link: function (scope, element, attr, ctrl) {
                var _self = this,
                    _initContent,
                    editor,
                    editorReady = false,
                    baseURL = "/wechatshop/static/js/lib/ueditor1_4_3/";

                var fexUE = {
                    initEditor: function () {
                        var _self = this;
                        if (typeof UE != 'undefined') {
                            editor = new UE.ui.Editor({
                                initialContent: _initContent,
                                toolbars: [
                                    ['source', 'undo', 'redo', 'bold', 'italic', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'simpleupload',
                                        'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist']
                                ],
                                initialFrameHeight: scope.height || 120,
                                autoHeightEnabled: false,
                                wordCount: false,
                                elementPathEnabled: false
                            });


                            editor.render(element[0]);
                            editor.ready(function () {
                                editorReady = true;
                                _self.setContent(_initContent);

                                function applyContentChange() {
                                    var content = editor.getContent();
                                    ctrl.$setViewValue(content);
                                    if (content.indexOf('<img class="loadingclass"') > 0) {
                                        setTimeout(function () {
                                            applyContentChange();
                                        }, 200);
                                    }
                                }
                                
                                editor.addListener('contentChange', function () {
                                    scope.$apply(function () {
                                        applyContentChange();
                                    });
                                });
                            });
                        } else {

                            addScript(baseURL + 'ueditor.config.js');
                            addScript(baseURL + 'ueditor.all.min.js', function () {
                                _self.initEditor();
                            })
                        }
                    },
                    setContent: function (content) {
                        if (editor && editorReady) {
                            editor.setContent(content);
                        }
                    }
                };

                /**
                 * 当Model改变值得时候赋值。
                 */
                ctrl.$render = function () {
                    _initContent = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
                    fexUE.setContent(_initContent);
                };

                fexUE.initEditor();
            }
        }
    }
);

app.filter('to_trusted', ['$sce', function ($sce) {
    return function (text) {
        return $sce.trustAsHtml(text);
    };
}]);

app.filter('plain', [function () {
    return function (text) {
        if (!text) {
            return text;
        }
        if (text.indexOf('<p>') === 0 && text.indexOf('</p>') === text.length - '</p>'.length) {
            return text.substr('<p>'.length, text.length - '<p>'.length - '</p>'.length);
        }
    };
}]);

app.filter('discount', [function () {
    return function (text) {
        try {
            var num = parseFloat(text);
            if (num <= 0) {
                return '无折扣';
            }
            if (num >= 1) {
                return '免费';
            }
            num = 1 - num;
            if (num * 10 === parseInt(num * 10)) {
                return (num * 10) + '折';
            }
            return (num * 10).toFixed(1) + '折';
        } catch (e) {
            return '无折扣';
        }
    };
}]);